package net.aizhuoyue;

import java.lang.management.ManagementFactory;
import java.util.Iterator;
import java.util.Set;

import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 
 * Spring在启动完成后执行方法
 * 
 * @author 00fly
 * @version [版本号, ${date?date}]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Component
public class Startup implements ApplicationListener<ContextRefreshedEvent>
{
    private static final Logger LOGGER = Logger.getLogger(Startup.class);
    
    @Autowired
    ServletContext servletContext;
    
    /**
     * 获取tomcat启动端口
     * 
     * @return
     * @throws JMException
     * @throws Exception
     * @see [类、类#方法、类#成员]
     */
    public String getTomcatPort()
        throws JMException
    {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();)
        {
            ObjectName obj = i.next();
            String port = obj.getKeyProperty("port");
            if (StringUtils.isNotBlank(port))
            {
                return port;
            }
        }
        // 偷懒，非tomcat服务器统一返回8080
        return "8080";
    }
    
    /**
     * 事件回调
     * 
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event)
    {
        if (event.getApplicationContext().getParent() == null && SystemUtils.IS_OS_WINDOWS)
        {
            try
            {
                LOGGER.info("now open Browser...");
                String url = String.format("http://127.0.0.1:%s%s", getTomcatPort(), servletContext.getContextPath());
                Runtime.getRuntime().exec("cmd.exe /c start /min " + url);
            }
            catch (Exception e)
            {
                LOGGER.error(e.getMessage(), e);
            }
        }
    }
}
